//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package impl

import (
	"fmt"
	"strings"

	"atomgit.com/openlinksaas-org/search-proxy/core"
)

var parserList []core.PageParser = []core.PageParser{
	&GitCodeParser{},
	&GithubParser{},
	&PkgGoParser{},
	&PkgsParser{},
	&PypiParser{},
	&RubygemsParser{},
	&BaiduParser{},
	&NpmjsParser{},
	&NugetParser{},
	&OsChinaParser{},
	&JuejinParser{},
}

func adjustText(content string) string {
	tmpList := []string{}
	for _, line := range strings.Split(content, "\n") {
		line = strings.Trim(line, " \t\r\n")
		if line != "" {
			tmpList = append(tmpList, line)
		}
	}
	return strings.Join(tmpList, "\n")
}

func Search(url string) ([]*core.SearchEntry, error) {
	for _, parser := range parserList {
		if parser.MatchUrl(url) {
			retList, err := parser.Parse(url)
			if err != nil {
				return nil, err
			}
			for _, entry := range retList {
				entry.Title = adjustText(entry.Title)
				summary := []rune(adjustText(entry.Summary))
				if len(summary) > 200 {
					summary = summary[:200]
				}
				entry.Summary = string(summary)
			}
			return retList, nil
		}
	}
	return nil, fmt.Errorf("no parser found")
}
